<template>
	<div class="userType_PC">
		<el-table
		  ref="multipleTable"
		  :data="tableData"
		  tooltip-effect="dark"
		  style="width: 100%"
			v-loading="isLoadingTable"
			highlight-current-row
		  @selection-change="handleSelectionChange"
		>
		  <el-table-column type="selection" width="40" align="center"></el-table-column>
			<el-table-column type="index" width="40" align="center"></el-table-column>
		  <el-table-column prop="username" label="用户名" align="center"></el-table-column>
		  <el-table-column prop="name" label="姓名" align="center"></el-table-column>
			<el-table-column prop="num" label="身份证号" align="center"></el-table-column>
			<el-table-column prop="position" label="职务" align="center"></el-table-column>
		  <el-table-column prop="mobilePhone" label="电话" align="center"></el-table-column>
		  <el-table-column label="状态" align="center">
				<template slot-scope="scope">
					<span v-if="scope.row.state == 'ENABLED'" style="color:green">启用</span>
					<span v-else style="color:red">禁用</span>
				</template>
			</el-table-column>
		  <el-table-column fixed="right" label="操作" width="360" align="center">
		    <template slot-scope="scope">
		      <el-button size="small" @click="handleViewAccount(scope.row)">查看</el-button>
		      <el-button size="small" @click="handleEditeAccount(scope.row)" :disabled="scope.row.operation == 'false'">编辑</el-button>
		      <el-button size="small" v-if="scope.row.state != 'ENABLED'" @click="handleStartAccount(scope.row)" :disabled="scope.row.operation == 'false'">启用</el-button>
					<el-button size="small" v-else @click="handleStopAccount(scope.row)" :disabled="scope.row.operation == 'false'">禁用</el-button>
		      <el-button size="small" type="danger" @click="handleDeleteAccount(scope.row)" :disabled="scope.row.operation == 'false'">删除</el-button>
		    </template>
		  </el-table-column>
		</el-table>
		<div class="pages">
		  <el-pagination
		    @current-change="handleCurrentChange"
		    :current-page.sync="currentPage"
		    :page-size="10"
		    layout="prev, pager, next, jumper"
		    :total="accountTotal"
		  ></el-pagination>
		</div>
		<!-- 用户弹框 -->
		<el-dialog :close-on-click-modal="false" :title="accountTitle" width="60%" :visible.sync="accountDialog" @close="handleClose('formData')">
			<el-form label-width="80px" label-position="top" :model="dialogFormData" :rules="formrules" ref="formData" v-loading='dialogLoading'>
				<el-row>
					<el-col :span="8" class="p-1">
						<el-form-item label="用户名" prop="username">
							<el-input v-model="dialogFormData.username" placeholder="请输入用户名" :readonly="isReadonly"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" class="p-1" v-show="submitType == 0 && !isReadonly">
						<el-form-item label="账户密码" prop="password">
							<el-input v-model="dialogFormData.password" type="password" placeholder="请输入初始化账号密码" :readonly="isReadonly"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" class="p-1" v-show="submitType == 1 && !isReadonly">
						<el-form-item label="重置账户密码" prop="password">
							<el-input v-model="dialogFormData.password" type="password" placeholder="请输入初始化账号密码" :readonly="isReadonly"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" class="p-1">
						<el-form-item label="真实姓名" prop="name">
							<el-input v-model="dialogFormData.name" placeholder="请输入真实姓名" :readonly="isReadonly"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" class="p-1">
						<el-form-item label="手机号码" prop="mobilePhone">
							<el-input v-model="dialogFormData.mobilePhone" placeholder="请输入手机号码" type="number" :readonly="isReadonly"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" class="p-1">
						<el-form-item label="身份证号" prop="num">
							<el-input v-model="dialogFormData.num" placeholder="请输入身份证号" :readonly="isReadonly"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" class="p-1">
						<el-form-item label="职务" prop="position">
							<el-input v-model="dialogFormData.position" placeholder="请输入用户职务" :readonly="isReadonly"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" class="p-1">
						<el-form-item label="权限" prop="permission">
							<el-input v-model="dialogFormData.permissionName" :readonly="true" v-show="isReadonly"></el-input>
							<el-select v-model="dialogFormData.permission" style="width:100%" v-show="!isReadonly">
								<el-option label="村社审批" value="WX_LAND_VILLAGE_AUDIT"></el-option>
								<el-option label="乡镇街道审批" value="WX_LAND_TOWN_AUDIT"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8" class="p-1">
						<!-- 新增 -->
						<el-form-item label="行政等级" prop="regionPermission" v-show="submitType == 0 || isEdite">
							<el-cascader v-model="dialogFormData.regionPermission" style="width:100%" :props="defaultPropsDistrict" ref="district" @change="handleSelectDistrict"></el-cascader>
						</el-form-item>
						<!-- 编辑 -->
						<el-form-item label="行政等级" v-show="submitType == 1 && !isEdite" prop="regionPermission">
							<el-input v-model="dialogFormData.regionName" :readonly="true" style="width:100%">
								<el-button slot="append" @click="handleChangeEdite" icon="el-icon-edit"></el-button>
							</el-input>
						</el-form-item>
						<!-- 查看 -->
						<el-form-item label="行政等级" v-show="submitType == 2" prop="regionPermission">
							<el-input v-model="dialogFormData.regionName" :readonly="true" style="width:100%"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" class="p-1">
						<el-form-item label="所属机构" prop="organizationId">
							<el-input style="width:100%" placeholder="请选择所属机构" v-model="dialogFormData.organizationName" :readonly="true" v-show="isReadonly"></el-input>
							<el-select style="width:100%" placeholder="可模糊查询" v-model="dialogFormData.organizationId" remote filterable :remote-method="bindQueryOrganizations" :loading="organization.loading" :disabled="isReadonly" v-show="!isReadonly">
								<el-option v-for="item in organization.list" :key="item.id" :label="item.name" :value="item.id"></el-option>
							</el-select>
						</el-form-item>						
					</el-col>
					<el-col :span="8" class="p-1">
						<el-form-item label="描述" prop="description">
							<el-input type='textarea' :rows="1" v-model="dialogFormData.description" placeholder="请输入" style="min-height: 40px;" :readonly="isReadonly"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" style="text-align: center;" v-show="!isReadonly">
				<el-button type="primary" @click="handleSubmit('formData')">提交</el-button>
				<el-button @click="handleReset('formData')" v-show="submitType == 0">重置</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
	import { getWxAccountTable , accountWxNewAdd , accountWxEdite , accountDelete  , SaveAccountState ,getWxAccountDetail , getOrganizationDistrict , getOrganizationList } from "@/api/project/system/account.js"
	import { getToken } from '@/utils/auth'
	import config from "@/config/index.js"
	import moment from 'moment'
	export default {
		props:{
			queryForm:{
				type:Object,
				default:{
					name:'',
					mobilePhone:'',
					state:''
				}
			}
		},
		data() {
			return {
				//新增微信用户
				dialogFormData:{
					username:"",
					password:"123456",
					name:"",
					mobilePhone:"",
					num:"",
					position:"",
					permission:"",
					description:"",
					regionPermission:"",
					organizationId:"",
					organizationName:""
				},
				//表单验证
				formrules:{
					username:[
						{required:true, message: '不能为空！', trigger: 'blur'}
					],
					password:[
						{required:true,message:'不能为空！',trigger:'blur'},
						{min:6,max:20,message:'限制在6~20位密码！',trigger:'blur'}
					],
					permission:[
						{required:true,message:"不能为空！",trigger:"change"}
					],
					regionPermission:[
						{required:true,message:"请选择！",trigger:"change"}
					],
				},
				//表格加载状态
				isLoadingTable:false,
				dialogLoading:false,
				// 表格数据
				tableData: [],
				// 多选操作数据
				accountTotal:0,
				currentPage: 1,
				//用户新增/编辑弹框标题
				accountTitle:'新增微信用户',
				accountDialog:false,
				//查看
				isReadonly:false,
				//编辑和新增判断
				submitType:0,//0:新增；1:编辑；2:查看
				//权限区域
				organizationDistrict:[],
				//机构列表
				organization:{
					list:[],
					loading:false
				},
				defaultPropsDistrict:{
					lazy:true,
					checkStrictly:true,
					lazyLoad(node,resolve){
						const { level , value } = node;
						getOrganizationDistrict({parentId:value}).then(res => {
							const nodes = res.data.map(item => ({
								value:item.id,
								label:item.name,
								leaf:level >= 3
							}))
							resolve(nodes);
						})
					}
				},
				isEdite:false,
			};
		},
		created() {
			this.handleInitData();
		},
		methods: {
			//数据初始化
			handleInitData:function () {
				this.handleGetTable();
				this.getOrganizationDistrict(1);
			},
			//WX端获取表格数据
			handleGetTable:function (page) {
				this.isLoadingTable = true;
				page != undefined ? this.currentPage = page : "";
				let params = {
					page:this.currentPage,
					size:10
				};
				Object.assign(params,this.queryForm);
				getWxAccountTable(params).then(res => {
					this.tableData = res.data.rows;
					this.accountTotal = res.data.total;
					this.isLoadingTable = false;
				})
			},
			//新增弹框
			handleNewAddAccount:function () {
				this.accountDialog = true;
				this.submitType = 0;
				this.accountTitle = "新增微信用户";
				// this.addFormValidation();
			},
			//新增/编辑提交按钮
			handleSubmit:function (formName) {
				var that = this;
				this.$refs['formData'].validate(valid => {
					if(valid){
						if(that.submitType == 0){
							let params = JSON.parse(JSON.stringify(that.dialogFormData));
							accountWxNewAdd(params).then(res => {
								this.accountDialog = false;
								this.handleGetTable(1);
							})
						}else{
							let params = JSON.parse(JSON.stringify(that.dialogFormData));
							accountWxEdite(params).then(res => {
								this.accountDialog = false;
								this.handleGetTable(1);
							})
						}
					}
				});
			},
			//弹框重置按钮
			handleReset:function (formName) {
				this.$refs[formName].resetFields();
			},
			//查看用户
			handleViewAccount:async function (row) {
				this.accountTitle = "用户详情";
				this.submitType = 2;				
				this.dialogLoading = true;
				this.accountDialog = true;
				// this.clearFormValidation();
				await getWxAccountDetail({id:row.userId}).then(res => {
					let obj = res.data;
					var {name:city,id:cityId} = obj.city ? obj.city : {};
					var {name:district,id:districtId} = obj.district ? obj.district : {};
					var {name:town,id:townId} = obj.town ? obj.town : {};
					var {name:village,id:villageId} = obj.village ? obj.village : {};
					obj['regionName'] = [city,district,town,village].filter(item => {
						return Boolean(item)
					}).join('/');
					obj['regionPermission'] = [cityId,districtId,townId,villageId].filter(item => {
						return Boolean(item)
					});
					if(obj.organization){
						obj['organizationId'] = obj.organization.id;
						obj['organizationName'] = obj.organization.name;
					};
					obj['permissionName'] = obj.permission == 'WX_LAND_VILLAGE_AUDIT' ? '村社审批' : "乡镇街道审批";
					this.dialogFormData = obj;
					this.isReadonly = true;
					this.dialogLoading = false;
				})
			},
			//编辑用户
			handleEditeAccount:async function (row) {
				this.accountTitle = "编辑用户";
				this.submitType = 1;
				this.dialogLoading = true;
				this.accountDialog = true;
				// this.addFormValidation();
				await getWxAccountDetail({id:row.userId}).then(res => {
					let obj = res.data;
					obj['password'] = "";
					var {name:city,id:cityId} = obj.city ? obj.city : {};
					var {name:district,id:districtId} = obj.district ? obj.district : {};
					var {name:town,id:townId} = obj.town ? obj.town : {};
					var {name:village,id:villageId} = obj.village ? obj.village : {};
					obj['regionName'] = [city,district,town,village].filter(item => {
						return Boolean(item)
					}).join('/');
					obj['regionPermission'] = [cityId,districtId,townId,villageId].filter(item => {
						return Boolean(item)
					});
					if(obj.organization){
						this.bindQueryOrganizations(obj.organization.name);
						obj['organizationId'] = obj.organization.id;
					};
					this.dialogFormData = obj;
					this.dialogLoading = false;
					// this.$refs['formData'].validate();
				})
			},
			//单条启用用户
			handleStartAccount:function (row) {
				this.$confirm('此操作将启用此账户, 是否继续?','提示',{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type:'warning'
				}).then(res => {
					let params = {
						ids:row.userId,
						state:row.state == "ENABLED" ? 'DISABLED':'ENABLED'
					};
					SaveAccountState(params).then(res => {
						this.$message.success('操作成功！');
						this.handleGetTable();
					})
				})
			},
			//单条禁用用户
			handleStopAccount:function (row) {
				this.$confirm('此操作将停用此账户, 是否继续?','提示',{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type:'warning'
				}).then(res => {
					let params = {
						ids:row.userId,
						state:row.state == "ENABLED" ? 'DISABLED':'ENABLED'
					};
					SaveAccountState(params).then(res => {
						this.$message.success('操作成功！');
						this.handleGetTable();
					})
				})
			},
			//单条删除用户
			handleDeleteAccount:function (row) {
				this.$confirm('此操作将永久删除此用户, 是否继续?','提示',{
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type:'warning'
				}).then(res => {
					let userId = row.userId;
					accountDelete({ids:userId}).then(res => {
						this.$message.success("操作成功！");
						this.handleGetTable();
					})
				})
			},
			//表格数据勾选回调
			handleSelectionChange:function (val) {
				this.$emit('bindMultipleSelection',val)
			},
			//换页查询
			handleCurrentChange:function (val) {
				this.handleGetTable(val);
			},
			//弹框关闭回调
			handleClose:function (formName) {
				this.dialogFormData = {
					username:"",
					password:"123456",
					name:"",
					mobilePhone:"",
					num:"",
					position:"",
					permission:"",
					description:"",
					regionPermission:""
				};
				this.isReadonly = false;
				this.$refs[formName].resetFields();
				this.isEdite = false;
			},
			//获取组织区域列表
			getOrganizationDistrict:function (id) {
				getOrganizationDistrict({parentId:id}).then(res => {
					this.organizationDistrict = res.data
				})
			},
			//区域权限修改
			handleChangeEdite:function(){
				this.isEdite = true;
			},
			//区域选择回调
			handleSelectDistrict:function (val) {
				this.dialogFormData['cityId'] = "";
				this.dialogFormData['districtId'] = "";
				this.dialogFormData['townId'] = "";
				this.dialogFormData['villageId'] = "";
				if(val){
					val[0] && (this.dialogFormData['cityId'] = val[0]);
					val[1] && (this.dialogFormData['districtId'] = val[1]);
					val[2] && (this.dialogFormData['townId'] = val[2]);
					val[3] && (this.dialogFormData['villageId'] = val[3]);
					this.dialogFormData['regionId'] = val[val.length - 1];
				}
			},
			//清空表单验证
			clearFormValidation:function () {
				this.formrules = {};
			},
			//加入表单验证
			addFormValidation:function () {
				this.formrules = {
					username:[
						{required:true, message: '不能为空！', trigger: 'change'}
					],
					password:[
						{required:true,message:'不能为空！',trigger:'blur'},
						{min:6,max:20,message:'限制在6~20位密码！',trigger:'blur'}
					],
					permission:[
						{required:true,message:"不能为空！",trigger:"change"}
					],
					regionPermission:[
						{required:true,message:"请选择！",trigger:"change"}
					],
				};
				this.submitType == 1 && (delete this.formrules['password']);
				if(this.submitType == 0){
					this.$nextTick(()=>{
						this.$refs['formData'].resetFields()
					})
				}
			},
			//机构列表模糊查询
			bindQueryOrganizations:function (name) {
				if(name){
					let params = {
						name:name
					};
					this.organization['loading'] = true;
					getOrganizationList(params).then(res => {
						this.organization['list'] = res.data;
						this.organization['loading'] = false;
					})
				}			
			}
		}
	};
</script>

<style lang="scss" scoped>
.can-container {
  padding: 20px;
	background:#fff;
  .title {
    font-size: 24px;
    font-weight: 500;
    color: rgba(72, 73, 77, 1);
    line-height: 33px;
  }
}

.btnsearch {
  background: #969799;
  color: white;
}

.btnReset {
  background: white;
  color: #969799;
}
.userList {
  margin: 30px 0px;
}
.btnuser {
  border: 1px solid #2e8ae6;
  color: #2e8ae6;
}
.pages {
  text-align: center;
  margin: 20px auto;
}
.rolesTitle{
  font-size: 14px;
  color: #333333;
}
.rolesBox{
  width: 100%;
  height: 308px;
	overflow: auto;
  background: #F8F8F8;
  border-radius:4px; 
  padding: 5px 15px;
  
}
.rolesBox p{
  padding: 5px;
  font-size: 12px;
  color: #333;
  display: flex;
  justify-content: space-between;
}
.rolesBox p.clickNo{
  color: #2e8ae6;
  cursor: pointer;
}
.rolesBox p:hover{
  color: #2e8ae6;
  cursor: pointer;
}
.p-1{
	padding:0 10px;
}
</style>

<style lang="scss" scoped>
	.avatar-uploader /deep/ .el-upload {
	    border: 1px dashed #d9d9d9;
	    border-radius: 6px;
	    cursor: pointer;
	    position: relative;
	    overflow: hidden;
			width:120px;
			height:120px;
			line-height: 120px;
	  }
	.avatar-uploader /deep/ .el-upload:hover {
		border-color: #409EFF;
	}
	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}
	.avatar {
		width: 120px;
		height: 120px;
		display: block;
	}
	/deep/ .el-textarea textarea{
		min-height: 40px !important;
	}
</style>
